package com.baselibrary.net.result;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * @author zhanglijie
 * @date 2018/9/30
 */
public class ResultJsonDeser implements JsonDeserializer<HttpResult<?>> {
    private static final String TAG = "ResultJsonDeser";

    @Override
    public HttpResult<?> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        HttpResult<Object> response = new HttpResult<>();
        boolean success = false;
        if (json.isJsonObject()) {
            JsonObject jsonObject = json.getAsJsonObject();
            if (jsonObject.has("success")) {
                success = jsonObject.get("success").getAsBoolean();
                response.setJson(json.toString());
                response.setSuccess(success);
            }

            if (jsonObject.has("msg")) {
                response.setMessage(jsonObject.get("msg").getAsString());
            }
            if (jsonObject.has("code")) {
                response.setCode(jsonObject.get("code").getAsInt());
            }

            if (success) {
                Type itemType = ((ParameterizedType) typeOfT).getActualTypeArguments()[0];
                response.setData(context.deserialize(jsonObject.get("data"), itemType));
                return response;
            }

        }
        return response;
    }
}
